1 package edu.jiangxin.apktoolbox.convert.color.colorspace; 2 3 import java.awt.color.ColorSpace; 4 5 public class HslColorSpace extends ColorSpace { 6 7 protected HslColorSpace(int type, int numComponents) { 8 super(type, numComponents); 9 } 10 11 public static HslColorSpace getInstance() { 12 return Holder.INSTANCE; 13 } 14 15 @Override 16 public float[] toRGB(float[] colorvalue) { 17 float h = colorvalue[0]; 18 float s = colorvalue[1]; 19 float l = colorvalue[2]; 20 21 float r, g, b; 22 23 if (s == 0f) { 24 r = g = b = l; 25 } else { 26 float q = l < 0.5f ? l * (1 + s) : l + s - l * s; 27 float p = 2 * l - q; 28 r = hueToRgb(p, q, h + 1/3f); 29 g = hueToRgb(p, q, h); 30 b = hueToRgb(p, q, h - 1/3f); 31 } 32 33 return new float[]{r, g, b}; 34 } 35 36 @Override 37 public float[] fromRGB(float[] rgbvalue) { 38 float r = rgbvalue[0]; 39 float g = rgbvalue[1]; 40 float b = rgbvalue[2]; 41 42 float max = Math.max(r, Math.max(g, b)); 43 float min = Math.min(r, Math.min(g, b)); 44 45 float h, s; 46 float l = (max + min) / 2; 47 48 if (max == min) { 49 h = s = 0f; 50 } else { 51 float delta = max - min; 52 s = l > 0.5f ? delta / (2 - max - min) : delta / (max + min); 53 if (max == r) { 54 h = (g - b) / delta + (g < b ? 6f : 0f); 55 } else if (max == g) { 56 h = (b - r) / delta + 2f; 57 } else { 58 h = (r - g) / delta + 4f; 59 } 60 h /= 6f; 61 } 62 63 return new float[]{h, s, l}; 64 } 65 66 @Override 67 public float[] toCIEXYZ(float[] colorvalue) { 68 float[] rgb = toRGB(colorvalue); 69 return ColorSpace.getInstance(CS_sRGB).toCIEXYZ(rgb); 70 } 71 72 @Override 73 public float[] fromCIEXYZ(float[] colorvalue) { 74 float[] rgb = ColorSpace.getInstance(CS_sRGB).fromCIEXYZ(colorvalue); 75 return fromRGB(rgb); 76 } 77 78 private float hueToRgb(float p, float q, float t) { 79 if (t < 0f) t += 1f; 80 if (t > 1f) t -= 1f; 81 if (t < 1/6f) return p + (q - p) * 6f * t; 82 if (t < 1/2f) return q; 83 if (t < 2/3f) return p + (q - p) * (2/3f - t) * 6f; 84 return p; 85 } 86 87 private static class Holder { 88 private static final HslColorSpace INSTANCE = new HslColorSpace(TYPE_HLS, 3); 89 } 90 }